package com.fitness.front.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.fitness.front.enums.VerificationEnum;
import com.fitness.front.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.fitness.front.constants.ServiceConstants.SMS_PREFIX;


@Slf4j
@Service
public class VerificationServiceImpl implements VerificationService{

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean verifyPhoneCode(String code, String phone, VerificationEnum verificationEnum) {
        String cacheKey = String.format(SMS_PREFIX,verificationEnum,phone);
        String cacheCode = redisTemplate.opsForValue().get(cacheKey);
        if(StrUtil.isBlank(cacheCode)){
            return false;
        }
        return cacheCode.equals(code);
    }

    @Override
    public String genVerifyCode(String phone, VerificationEnum verificationEnum) {
        String cacheKey = String.format(SMS_PREFIX,verificationEnum,phone);
        if(StrUtil.isBlank(phone)){
            log.error(String.format("生成验证码异常：phone:%1s,type:%s",phone,verificationEnum));
            throw new BizException("生成验证码失败!");
        }
        if(redisTemplate.hasKey(cacheKey)){
            return redisTemplate.opsForValue().get(cacheKey);
        }
        String code = RandomUtil.randomNumbers(6);
        redisTemplate.opsForValue().set(cacheKey,code,5L, TimeUnit.MINUTES);
        return code;
    }
}
